package com.expert.interceptor;

import com.expert.Mapper.UserMapper;
import com.expert.constant.JwtClaimConstant;
import com.expert.context.BaseContext;
import com.expert.exception.AccessTokenException;
import com.expert.properties.JwtProperties;
import com.expert.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @ClassName: jwtTokenInterceptor
 * @Author: cxs
 * @Date: 2024/01/18 18:42
 * @Description:
 **/
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截URI:" + request.getRequestURI());
        if (!(handler instanceof HandlerMethod)) {
            log.info("静态资源，放行：" + request.getRequestURL());
            return true;
        }
        //获取Token
        String token = request.getHeader(jwtProperties.getAccessTokenName());
        try {
            log.info("jwt令牌校验：{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAccessSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimConstant.USER_ID).toString());
            BaseContext.setCurrentId(userId);
            request.getSession().setAttribute("user-id",userId);
            log.info("当前用户id:{}", userId);
            return true;
        } catch (Exception ex) {
            throw new AccessTokenException("");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
        request.getSession().removeAttribute("user-id");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
